package gateway

import (
	"net/http"
	"sync"
	"time"
)

type CacheEntry struct {
	Response *http.Response
	ExpireAt time.Time	// 过期时间
}

// ResponseCache 响应缓存
type ResponseCache struct {
	cache map[string]*CacheEntry
	mu sync.RWMutex
}

// NewResponseCache 创建响应缓存
func NewResponseCache() *ResponseCache {
	return &ResponseCache{
		cache: make(map[string]*CacheEntry),
	}
}

// Get
func (rc *ResponseCache) Get(key string) (*http.Response, bool) {
	rc.mu.RLock()
	defer rc.mu.RUnlock()
	resp, ok :=rc.cache[key]
	if !ok {
		return nil, false
	}
	if time.Now().After(resp.ExpireAt) {
		delete(rc.cache, key)
		return nil, false
	}
	return resp.Response, true
}

// Set
func (rc *ResponseCache) Set(key string, resp *http.Response, duration time.Duration) {
	rc.mu.Lock()
	defer rc.mu.Unlock()
	rc.cache[key] = &CacheEntry{
		Response: resp,
		ExpireAt: time.Now().Add(duration),
	}
}



